package com.xiwen.xiwenzhang.user.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.xiwen.common.baseentity.ResponsEntity;
import com.xiwen.common.utils.ResultUtil;
import com.xiwen.plugin.mybatisplus.generator.util.UtilsConst;
import com.xiwen.xiwenzhang.permission.Service.SysPermissionService;
import com.xiwen.xiwenzhang.permission.entity.SysPermissionEntity;
import com.xiwen.xiwenzhang.user.entity.SysUserEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Dep 登录控制器
 * @Author xiwen
 * @Date 2021/10/28 21:14
 */
@Controller
@Slf4j
@AllArgsConstructor
public class LoginController {

    @Autowired
    private  SysPermissionService sysPermissionService;

    @PostMapping("/login")
    @ResponseBody
    public ResponsEntity login(HttpServletRequest request, String username, String password, String verification) {
        //判断验证码
        if (!CaptchaUtil.ver(verification, request)) {
            // 清除session中的验证码
            CaptchaUtil.clear(request);
            return ResultUtil.error("验证码错误！");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResultUtil.error("用户已经被锁定不能登录，请联系管理员！");
        } catch (AuthenticationException e) {
            token.clear();
            return ResultUtil.error("用户名或者密码错误！");
        }

        return ResultUtil.success("登录成功！");
    }


    /**
     * @Dep 退出
     * @Author xiwen
     * @Date 2021/10/28 19:41
     */
    @GetMapping("/signOut")
    public String signOut() {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            subject.logout();
        }
        return UtilsConst.ADMIN_PREFIX +"login";
    }

    //添加文章
    @GetMapping("/articleAdd")
    public String articleAdd() {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            subject.logout();
        }
        return UtilsConst.ADMIN_PREFIX +"menu-add2.html";
    }
    /**
     * 获取验证码图片
     * Gets captcha code.
     * @param request  the request
     * @param response the response
     */
    @RequestMapping("/verificationCode")
    public void getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 48);
        captcha.setLen(2);
        CaptchaUtil.out(captcha, request, response);
    }


    //跳转到登录页面
    @GetMapping("/admin")
    public String admin() {
        return UtilsConst.ADMIN_PREFIX +"login";
    }

    //登陆成功跳转
    @GetMapping("/loginSuccess")
    public String loginSuccess(Model model) {
        String userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getId();
        List<SysPermissionEntity> menuList=sysPermissionService.findMenuByUserId(userId);
        model.addAttribute("menuTree", menuList);
        return UtilsConst.ADMIN_PREFIX +"index";
    }

    //登陆成功欢迎页面
    @GetMapping("/welcome")
    public String welcome() {
        return UtilsConst.ADMIN_PREFIX +"welcome";
    }


}
